import requests
from django.conf import settings
from django.http import JsonResponse, FileResponse, HttpResponseForbidden
import os
from .paginate import paginate_queryset
from .permission import TaskPermission
from .utils import check_due_tasks, send_dingtalk_message
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView, CreateView, DeleteView
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.http import Http404
from rest_framework import viewsets, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from .forms import TaskForm
from .models import TaskImage, TaskActivity
from .seralizers import TaskSerializer
from .signals import task_details, task_created, task_edited, task_deleted
from django.views.generic import TemplateView, UpdateView
from django.contrib.auth.models import User
from django.urls import reverse_lazy
from django.db.models import Q, Count
from django.contrib import messages
import csv
import xlwt
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views import View
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, landscape
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from io import BytesIO, TextIOWrapper
from datetime import datetime
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Task
import json
import pytz

from .visualization import generate_time_series_data


# API Views
class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    permission_classes = [TaskPermission]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['status', 'assigned_to', 'Projectname', 'system', 'testprogress',
                        'ProjectManager', 'ProductManager', 'DevelopmentEngineer', 'TestEngineer']
    search_fields = ['title', 'description', 'ProjectManager', 'ProductManager', 'DevelopmentEngineer', 'TestEngineer']
    ordering_fields = ['due_date', 'created_at', 'status', 'startdate', 'enddate', 'testprogress']

    def get_queryset(self):
        # 匿名用户可以看到所有公共任务
        if not self.request.user.is_authenticated:
            return Task.objects.all()
        # 已登录用户可以看到分配给他们的任务或由他们创建的任务
        user = self.request.user
        return Task.objects.filter(assigned_to=user) | Task.objects.filter(created_by=user) | Task.objects.filter(
            assigned_to=None, created_by=None)

    def perform_create(self, serializer):
        # 如果用户已登录，将其设置为创建者
        if self.request.user.is_authenticated:
            serializer.save(created_by=self.request.user)
        else:
            serializer.save()

    @action(detail=False, methods=['get'])
    def my_tasks(self, request):
        if not request.user.is_authenticated:
            return Response({"detail": "Authentication required for this endpoint."}, status=401)
        tasks = Task.objects.filter(assigned_to=request.user)
        serializer = self.get_serializer(tasks, many=True)
        return Response(serializer.data)


class TaskListView(ListView):
    model = Task
    template_name = 'tasks/task_list.html'
    context_object_name = 'tasks'

    def get_queryset(self):
        queryset = Task.objects.all()

        # 获取筛选参数
        project = self.request.GET.get('project')
        system = self.request.GET.get('system')
        test_engineer = self.request.GET.get('test_engineer')
        dev_engineer = self.request.GET.get('dev_engineer')
        project_manager = self.request.GET.get('project_manager')
        product_manager = self.request.GET.get('product_manager')
        # 任务状态筛选
        status = self.request.GET.get('status')

        # 应用筛选条件
        if status:
            queryset = queryset.filter(status=status)
        if project:
            queryset = queryset.filter(Projectname__icontains=project)
        if system:
            queryset = queryset.filter(system__icontains=system)
        if test_engineer:
            queryset = queryset.filter(TestEngineer__icontains=test_engineer)
        if dev_engineer:
            queryset = queryset.filter(DevelopmentEngineer__icontains=dev_engineer)
        if project_manager:
            queryset = queryset.filter(ProjectManager__icontains=project_manager)
        if product_manager:
            queryset = queryset.filter(ProductManager__icontains=product_manager)

        # 用户权限筛选
        if not self.request.user.is_authenticated:
            return queryset

        # 已登录用户可以看到分配给他们的任务或由他们创建的任务
        user = self.request.user
        return queryset.filter(Q(assigned_to=user) | Q(created_by=user) | Q(assigned_to=None, created_by=None))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # 获取静态文件路径

        # 获取筛选后的任务列表
        queryset = self.get_queryset()

        # 为每种状态的任务创建单独的分页器
        todo_tasks = queryset.filter(status='todo').order_by('-due_date')
        in_progress_tasks = queryset.filter(status='in_progress').order_by('-due_date')
        done_tasks = queryset.filter(status='done').order_by('-due_date')

        context['todo_tasks'] = todo_tasks
        context['in_progress_tasks'] = in_progress_tasks
        context['done_tasks'] = done_tasks
        context['todo_tasks'] = todo_tasks

        def get_unique_values(field_name):
            # 获取所有非空值
            values = Task.objects.exclude(**{f"{field_name}__isnull": True}).exclude(**{field_name: ""}).values_list(
                field_name, flat=True)
            # 清理值（去除前后空格）并去重
            cleaned_values = set()
            for value in values:
                if value:  # 确保值不为None或空字符串
                    # 去除前后空格并添加到集合中
                    cleaned_value = value.strip()
                    if cleaned_value:  # 确保清理后的值不为空
                        cleaned_values.add(cleaned_value)
            # 转换为排序列表
            return sorted(list(cleaned_values))

        # 获取所有可用的筛选选项，并确保彻底去重
        context['projects'] = get_unique_values('Projectname')
        context['systems'] = get_unique_values('system')
        context['test_engineers'] = get_unique_values('TestEngineer')
        context['dev_engineers'] = get_unique_values('DevelopmentEngineer')
        context['project_managers'] = get_unique_values('ProjectManager')
        context['product_managers'] = get_unique_values('ProductManager')
        context['statuses'] = ('todo', 'in_progress', 'done')

        # 保存当前筛选条件，用于表单回显和分页链接
        context['current_filters'] = {
            'project': self.request.GET.get('project', ''),
            'system': self.request.GET.get('system', ''),
            'test_engineer': self.request.GET.get('test_engineer', ''),
            'dev_engineer': self.request.GET.get('dev_engineer', ''),
            'project_manager': self.request.GET.get('project_manager', ''),
            'product_manager': self.request.GET.get('product_manager', ''),
            'status': self.request.GET.get('status', ''),
        }

        # 构建分页URL参数（不包含page参数）
        filter_params = '&'.join([f"{key}={value}" for key, value in context['current_filters'].items() if value])
        if filter_params:
            context['pagination_params'] = f"&{filter_params}"
        else:
            context['pagination_params'] = ""

        list_data = []
        for activity in TaskActivity.objects.all().order_by('-timestamp'):
            list_data.append({
                'activity_type': activity.activity_type,
                'timestamp': activity.timestamp,
                'user': activity.user.username,

            })
        recent_activities = list_data
        context['recent_activities'] = recent_activities

        return context


class TaskDetailView(DetailView):
    model = Task
    template_name = 'tasks/task_detail.html'
    context_object_name = 'task'

    # 记录访问
    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)
        # 记录访问
        task_details.send(sender=self, user=request.user, instance=self.get_object())
        return response


class TaskCreateView(CreateView):
    model = Task
    form_class = TaskForm
    template_name = 'tasks/task_form.html'
    success_url = reverse_lazy('task-list')

    def form_valid(self, form):
        # 如果用户已登录，将其设置为创建者
        if self.request.user.is_authenticated:
            form.instance.created_by = self.request.user

        # 设置发送通知标志
        form.instance._send_notification = form.cleaned_data.get('send_notification', False)

        # 保存任务
        response = super().form_valid(form)

        # 处理额外的图片 - 直接从request.FILES获取
        additional_images = self.request.FILES.getlist('additional_images')
        captions = form.cleaned_data.get('image_captions', '').split('\n')

        # 确保有足够的说明
        while len(captions) < len(additional_images):
            captions.append('')

        # 保存每张图片
        for i, image_file in enumerate(additional_images):
            caption = captions[i].strip() if i < len(captions) else ''
            TaskImage.objects.create(
                task=self.object,
                image=image_file,
                caption=caption
            )

        if additional_images:
            messages.success(self.request, f'成功上传了 {len(additional_images)} 张额外图片')

        return response

    def form_invalid(self, form):
        # 打印表单错误信息
        print(f"表单错误: {form.errors}")
        return super().form_invalid(form)

    def post(self, request, *args, **kwargs):
        # 打印请求数据
        print(f"POST 数据: {request.POST}")
        print(f"FILES 数据: {request.FILES}")
        return super().post(request, *args, **kwargs)

    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)
        # 记录创建事件
        # task_created.send(sender=self, user=request.user, instance=self.get_object())
        return response


class TaskUpdateView(UpdateView):
    model = Task
    form_class = TaskForm
    template_name = 'tasks/task_form.html'
    success_url = reverse_lazy('task-list')

    # 用户没有登录，不允许更新

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['task_images'] = TaskImage.objects.filter(task=self.object)
        return context

    def form_valid(self, form):
        # 保存任务
        response = super().form_valid(form)

        # 处理额外的图片 - 直接从request.FILES获取
        additional_images = self.request.FILES.getlist('additional_images')
        captions = form.cleaned_data.get('image_captions', '').split('\n')

        # 确保有足够的说明
        while len(captions) < len(additional_images):
            captions.append('')

        # 保存每张图片
        for i, image_file in enumerate(additional_images):
            caption = captions[i].strip() if i < len(captions) else ''
            TaskImage.objects.create(
                task=self.object,
                image=image_file,
                caption=caption
            )

        if additional_images:
            messages.success(self.request, f'成功上传了 {len(additional_images)} 张额外图片')

        return response

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect('login')
        response = super().dispatch(request, *args, **kwargs)
        # 记录访问
        # task_edited.send(sender=self, user=request.user, instance=self.get_object())
        return response


# 添加删除图片的视图
@login_required
def delete_task_image(request, pk):
    image = get_object_or_404(TaskImage, pk=pk)
    task = image.task

    # 检查权限
    if task.created_by != request.user and not request.user.is_staff:
        messages.error(request, '您没有权限删除此图片')
        return redirect('task-update', pk=task.pk)

    if request.method == 'POST':
        image.delete()
        messages.success(request, '图片已成功删除')

    return redirect('task-update', pk=task.pk)


class TaskDeleteView(DeleteView):
    model = Task
    template_name = 'tasks/task_confirm_delete.html'
    success_url = reverse_lazy('task-list')

    def dispatch(self, request, *args, **kwargs):
        task = self.get_object()
        # 如果任务有创建者且不是当前用户，则不能删除
        if task.created_by != request.user:
            messages.error(request, '您没有权限删除此任务')
            return redirect('task-list')
        if task.created_by != request.user.is_authenticated:
            return redirect('login')
        if request.method == 'POST':
            task.delete()
            messages.success(request, f'"{task.title}" 任务已删除')
            return redirect(self.success_url)
        return render(request, self.template_name, {'object': task})


def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('task-list')
    else:
        form = UserCreationForm()
    return render(request, 'tasks/register.html', {'form': form})


@login_required
def task_done(request, pk):
    """任务完成视图"""
    task = get_object_or_404(Task, pk=pk)
    task.status = 'done'
    task.testprogress = '100'
    task.save()
    return redirect('task-list')


@login_required
def task_progress(request, pk):
    """任务进度视图"""
    task = get_object_or_404(Task, pk=pk)
    task.status = 'in_progress'
    task.testprogress = '10'
    task.save()
    return redirect('task-list')


def test_dingtalk_notification(request):
    """测试钉钉通知功能的视图"""
    message = "### 测试通知\n\n这是一条来自任务管理系统的测试消息。\n\n> 如果您收到此消息，说明钉钉通知功能配置正确。"
    result = send_dingtalk_message(message)
    return JsonResponse({"status": "success", "result": result})


def test_due_tasks_notification(request):
    """测试到期任务通知功能的视图"""
    result = check_due_tasks()
    return JsonResponse({"status": "success", "result": result})


class UserCenterView(LoginRequiredMixin, TemplateView):
    template_name = 'tasks/user_center.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = self.request.user

        # 获取用户的任务统计
        user_tasks = Task.objects.filter(Q(assigned_to=user) | Q(created_by=user))

        # 任务状态统计
        task_stats = user_tasks.values('status').annotate(count=Count('status'))
        stats_dict = {item['status']: item['count'] for item in task_stats}

        context['total_tasks'] = user_tasks.count()
        context['todo_count'] = stats_dict.get('todo', 0)
        context['in_progress_count'] = stats_dict.get('in_progress', 0)
        context['done_count'] = stats_dict.get('done', 0)

        # 获取用户最近的任务
        context['recent_tasks'] = user_tasks.order_by('-created_at')[:5]

        # 获取用户创建的任务
        context['created_tasks'] = Task.objects.filter(created_by=user).order_by('-created_at')[:5]

        # 获取分配给用户的任务
        context['assigned_tasks'] = Task.objects.filter(assigned_to=user).order_by('-created_at')[:5]

        # 获取即将到期的任务
        from datetime import datetime, timedelta
        today = datetime.now().date()
        upcoming_deadline = today + timedelta(days=7)  # 未来7天内到期的任务
        context['upcoming_tasks'] = user_tasks.filter(
            due_date__gte=today,
            due_date__lte=upcoming_deadline,
            status__in=['todo', 'in_progress']
        ).order_by('due_date')

        return context


class UserProfileUpdateView(LoginRequiredMixin, UpdateView):
    model = User
    template_name = 'tasks/user_profile_update.html'
    fields = ['username', 'first_name', 'last_name', 'email']
    success_url = reverse_lazy('user-center')

    def get_object(self, queryset=None):
        return self.request.user

    def form_valid(self, form):
        messages.success(self.request, '个人资料已成功更新！')
        return super().form_valid(form)


def get_info_from_api(request):
    """从API获取测试人员信息"""
    # 获取API的URL
    api_url = "https://oa.yafex.cn/include/of/index.php?c=of_base_com_com&a=paging"
    payload = {'method': 'model\\user\\itTeam::userPaging',
               'items': '',
               'size': '',
               'page': '',
               'sort': '',
               'params': '{"search":{"teamId":"15"}}'
               }
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'origin': 'https://oa.yafex.cn'
    }
    # 发送GET请求获取API数据
    response = requests.post(api_url, payload, headers=headers)
    result = response.json()['data']
    return JsonResponse(result, safe=False)


class ExportTasksView(View):
    """导出任务数据的视图"""

    @method_decorator(login_required)
    def get(self, request):
        # 获取导出格式
        export_format = request.GET.get('format', 'csv')

        # 获取筛选参数
        project = request.GET.get('project', '')
        system = request.GET.get('system', '')
        test_engineer = request.GET.get('test_engineer', '')
        dev_engineer = request.GET.get('dev_engineer', '')
        project_manager = request.GET.get('project_manager', '')
        product_manager = request.GET.get('product_manager', '')
        status = request.GET.get('status', '')

        # 查询任务
        tasks = Task.objects.all()

        # 应用筛选条件
        if project:
            tasks = tasks.filter(Projectname__icontains=project)
        if system:
            tasks = tasks.filter(system__icontains=system)
        if test_engineer:
            tasks = tasks.filter(TestEngineer__icontains=test_engineer)
        if dev_engineer:
            tasks = tasks.filter(DevelopmentEngineer__icontains=dev_engineer)
        if project_manager:
            tasks = tasks.filter(ProjectManager__icontains=project_manager)
        if product_manager:
            tasks = tasks.filter(ProductManager__icontains=product_manager)
        if status:
            tasks = tasks.filter(status=status)

        # 根据格式导出
        if export_format == 'csv':
            return self.export_csv(tasks)
        elif export_format == 'excel':
            return self.export_excel(tasks)
        elif export_format == 'pdf':
            return self.export_pdf(tasks)
        else:
            return HttpResponse('不支持的导出格式', status=400)

    def export_csv(self, tasks):
        """导出为CSV格式"""
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = f'attachment; filename="tasks_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv"'

        # 创建CSV写入器
        writer = csv.writer(response)

        # 写入表头
        writer.writerow([
            'ID', '标题', '描述', '状态', '项目', '系统',
            '测试负责人', '开发负责人', '项目经理', '产品经理',
            '测试进度', '创建时间', '截止日期', '完成日期',
            '分配给', '创建者', '需求链接', '测试链接'
        ])

        # 写入数据
        for task in tasks:
            writer.writerow([
                task.id, task.title, task.description, self.get_status_display(task.status),
                task.Projectname, task.system, task.TestEngineer, task.DevelopmentEngineer,
                task.ProjectManager, task.ProductManager, task.testprogress,
                task.created_at.strftime('%Y-%m-%d %H:%M') if task.created_at else '',
                task.due_date.strftime('%Y-%m-%d') if task.due_date else '',
                task.enddate.strftime('%Y-%m-%d') if task.enddate else '',
                task.assigned_to.username if task.assigned_to else '',
                task.created_by.username if task.created_by else '',
                task.Demandlink, task.Testlink
            ])

        return response

    def export_excel(self, tasks):
        """导出为Excel格式"""
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = f'attachment; filename="tasks_{datetime.now().strftime("%Y%m%d_%H%M%S")}.xls"'

        # 创建工作簿
        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet('任务列表')

        # 设置样式
        header_style = xlwt.XFStyle()
        header_font = xlwt.Font()
        header_font.bold = True
        header_style.font = header_font

        # 写入表头
        headers = [
            'ID', '标题', '描述', '状态', '项目', '系统',
            '测试负责人', '开发负责人', '项目经理', '产品经理',
            '测试进度', '创建时间', '截止日期', '完成日期',
            '分配给', '创建者', '需求链接', '测试链接'
        ]

        for col_idx, header in enumerate(headers):
            ws.write(0, col_idx, header, header_style)
            # 设置列宽
            ws.col(col_idx).width = 256 * 20  # 20个字符宽度

        # 写入数据
        for row_idx, task in enumerate(tasks, 1):
            ws.write(row_idx, 0, task.id)
            ws.write(row_idx, 1, task.title)
            ws.write(row_idx, 2, task.description)
            ws.write(row_idx, 3, self.get_status_display(task.status))
            ws.write(row_idx, 4, task.Projectname or '')
            ws.write(row_idx, 5, task.system or '')
            ws.write(row_idx, 6, task.TestEngineer or '')
            ws.write(row_idx, 7, task.DevelopmentEngineer or '')
            ws.write(row_idx, 8, task.ProjectManager or '')
            ws.write(row_idx, 9, task.ProductManager or '')
            ws.write(row_idx, 10, task.testprogress or '')
            ws.write(row_idx, 11, task.created_at.strftime('%Y-%m-%d %H:%M') if task.created_at else '')
            ws.write(row_idx, 12, task.due_date.strftime('%Y-%m-%d') if task.due_date else '')
            ws.write(row_idx, 13, task.enddate.strftime('%Y-%m-%d') if task.enddate else '')
            ws.write(row_idx, 14, task.assigned_to.username if task.assigned_to else '')
            ws.write(row_idx, 15, task.created_by.username if task.created_by else '')
            ws.write(row_idx, 16, task.Demandlink or '')
            ws.write(row_idx, 17, task.Testlink or '')

        wb.save(response)
        return response

    def export_pdf(self, tasks):
        """导出为PDF格式"""
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="tasks_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'

        # 创建PDF文档
        buffer = BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=landscape(letter))
        elements = []

        # 添加标题
        styles = getSampleStyleSheet()
        elements.append(
            Paragraph(f"任务列表 - 导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", styles['Title']))
        elements.append(Spacer(1, 12))

        # 准备数据
        data = [
            ['ID', '标题', '描述', '状态', '项目', '系统', '测试负责人', '开发负责人',
             '项目经理', '产品经理', '测试进度', '创建时间',
             '截止日期', '完成日期', '分配给', '创建者', '需求链接', '测试链接']
        ]

        for task in tasks:
            data.append([
                str(task.id),
                task.title,
                task.description,
                self.get_status_display(task.status),
                task.Projectname or '',
                task.system or '',
                task.TestEngineer or '',
                task.DevelopmentEngineer or '',
                task.ProjectManager or '',
                task.ProductManager or '',
                task.testprogress or '',
                task.created_at.strftime('%Y-%m-%d %H:%M') if task.created_at else '',
                task.due_date.strftime('%Y-%m-%d') if task.due_date else '',
                task.enddate.strftime('%Y-%m-%d') if task.enddate else '',
                task.assigned_to.username if task.assigned_to else '',
                task.created_by.username if task.created_by else ''
            ])

        # 创建表格
        table = Table(data, repeatRows=1)

        # 设置表格样式
        table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, 0), 12),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
            ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ]))

        elements.append(table)

        # 构建PDF
        doc.build(elements)
        pdf = buffer.getvalue()
        buffer.close()

        response.write(pdf)
        return response

    def get_status_display(self, status):
        """获取状态的显示文本"""
        status_map = {
            'todo': '待办',
            'in_progress': '进行中',
            'done': '已完成'
        }
        return status_map.get(status, status)


class ExportTasksFormView(LoginRequiredMixin, TemplateView):
    """导出任务表单视图"""
    template_name = 'tasks/export_tasks.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # 使用Python的set进行彻底去重
        def get_unique_values(field_name):
            # 获取所有非空值
            values = Task.objects.exclude(**{f"{field_name}__isnull": True}).exclude(**{field_name: ""}).values_list(
                field_name, flat=True)
            # 清理值（去除前后空格）并去重
            cleaned_values = set()
            for value in values:
                if value:  # 确保值不为None或空字符串
                    # 去除前后空格并添加到集合中
                    cleaned_value = value.strip()
                    if cleaned_value:  # 确保清理后的值不为空
                        cleaned_values.add(cleaned_value)
            # 转换为排序列表
            return sorted(list(cleaned_values))

        # 获取所有可用的筛选选项，并确保彻底去重
        context['projects'] = get_unique_values('Projectname')
        context['systems'] = get_unique_values('system')
        context['test_engineers'] = get_unique_values('TestEngineer')
        context['dev_engineers'] = get_unique_values('DevelopmentEngineer')
        context['project_managers'] = get_unique_values('ProjectManager')
        context['product_managers'] = get_unique_values('ProductManager')

        return context


def not_found_view(request, exception):
    """自定义404错误处理视图"""
    return render(request, 'tasks/404.html', status=404)


def dashboard(request):
    # 统计数量
    tasks_count = Task.objects.filter(created_by_id=request.user.id).count()  # 任务总数
    completed_tasks_count = Task.objects.filter(status='done', created_by_id=request.user.id).count()
    todo_tasks_count = Task.objects.filter(status='todo', created_by_id=request.user.id).count()
    in_progress_tasks_count = Task.objects.filter(status='in_progress',created_by_id=request.user.id).count()
    # overdue_tasks_count = Task.objects.filter(due_date__lt=timezone.now()).count()
    # 最近任务记录
    tasks = Task.objects.order_by('-created_at').filter(created_by_id=request.user.id) #
    recent_tasks = paginate_queryset(request, tasks, 5)

    tz = pytz.timezone(settings.TIME_ZONE)

    # 获取时间序列数据
    daily_data = generate_time_series_data(mode='daily', tz=tz)
    monthly_data = generate_time_series_data(mode='monthly', tz=tz)
    yearly_data = generate_time_series_data(mode='yearly', tz=tz)
    # 最近活动列表
    recent_activities = []
    activities = Task.objects.all().order_by('-created_at')[:5]
    for activity in activities:
        action = activity.title.split(': ')[0]
        timestamp = activity.created_at
        description = f"{activity.description} 执行结果为： {activity.status}"
        recent_activities.append({
            'action': action,
            'timestamp': timestamp,
            'description': description
        })

    context = {
        'tasks_count': tasks_count,
        'completed_tasks_count': completed_tasks_count,
        'todo_tasks_count': todo_tasks_count,
        'in_progress_tasks_count': in_progress_tasks_count,
        # 'overdue_tasks_count': overdue_tasks_count,
        'recent_tasks': recent_tasks,
        'recent_activities': recent_activities,
        'daily_data_json': json.dumps(daily_data),
        'monthly_data_json': json.dumps(monthly_data),
        'yearly_data_json': json.dumps(yearly_data),
    }

    return render(request, 'tasks/dashboard.html', context)


def import_excel(request):
    if request.method == 'POST' and request.FILES['excel_file']:
        file = request.FILES['excel_file']
        try:
            wrapper = TextIOWrapper(file.file)
            reader = csv.DictReader(wrapper)
            count = 0
            for row in reader:
                title = row.get('title') or row.get('标题')
                description = row.get('description') or row.get('描述')
                status = row.get('status') or row.get('状态')
                Projectname = row.get('Projectname') or row.get('项目')
                system = row.get('system') or row.get('系统')
                ProjectManager = row.get('ProjectManager') or row.get('项目经理')
                ProductManager = row.get('ProductManager') or row.get('产品经理')
                DevelopmentEngineer = row.get('DevelopmentEngineer') or row.get('开发负责人')
                TestEngineer = row.get('TestEngineer') or row.get('测试负责人')
                Demandlink = row.get('Demandlink') or row.get('需求链接')
                Testlink = row.get('Testlink') or row.get('测试链接')
                testprogress = row.get('testprogress') or row.get('测试进度')

                if title:
                    Task.objects.create(
                        title=title,
                        description=description,
                        status=status,
                        Demandlink=Demandlink,
                        Testlink=Testlink,
                        Projectname=Projectname,
                        ProductManager=ProductManager,
                        ProjectManager=ProjectManager,
                        DevelopmentEngineer=DevelopmentEngineer,
                        TestEngineer=TestEngineer,
                        system=system,
                        testprogress=testprogress

                    )
                    count += 1
            messages.success(request, f"成功导入{count}条任务。")
        except Exception as e:
            messages.error(request, f"导入失败：{str(e)}")
    return redirect('task-list')


def export_template(request):
    """
    导出media/excel_template目录下的 模版文件.csv
    """
    filename = '模版文件.csv'
    file_path = os.path.join(settings.EXCEL_ROOT, filename)
    if not os.path.exists(file_path):
        messages.error(request, '模板文件不存在！')
        return redirect('task-list')
    response = FileResponse(open(file_path, 'rb'), as_attachment=True, filename=filename)
    return response
